import NetService from './net.service'
import { ref, reactive } from 'vue'
import { Service, injectable, mutex } from './service'
import { StationMap } from '@/pages/design/service/item/read.type'

@injectable
export default class StationsService extends Service {
  public stations = ref<StationMap[]>([])

  public addData = reactive({
    id: '',
    center: 0,
    length: 0
  })

  /** 站台下拉选所需数据 */
  public stationOption = ref([{ value: '', label: '' }])

  private netService = new NetService()

  @mutex
  async load () {
    const res = await this.netService.get('/stations/list')
    if (res?.success) {
      if (this.stations.value.length === 0) {
        res?.data.forEach((item: { direction: string | number; id: number | string }, index: number) => {
          item.id = item.id.toString(16).replace('"', '').replace('"', '').toUpperCase()
        })
        this.stations.value = res?.data
      }
    }
  }

  async add (params: {
    id: string;
    name: string;
    center: number;
    length: number;
  }) {
    const res = await this.netService.post('/stations/insert', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      params.length = Number(params.length)
      params.center = Number(params.center)
      this.stations.value.push(params)
    }
    return res
  }

  async change (params: {
    id: string;
    name: string;
    center: number;
    length: number;
  }) {
    const res = await this.netService.post('/stations/update', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      const delIndex = this.stations.value.findIndex((e, index) => {
        return e.id === params.id
      })
      this.stations.value.splice(delIndex, 1, params)
    }
    return res
  }

  async del (params: { id: string }) {
    const res = await this.netService.post('/stations/delete', params, 'posturl')
    if (res?.success) {
      const delIndex = this.stations.value.findIndex((e, index) => {
        return e.id === parseInt(params.id).toString(16).toUpperCase()
      })
      this.stations.value.splice(delIndex, 1)
    }
    return res
  }
}
